<template>
	<view>
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<u-sticky class="u-sticky">
			<view class="padding-sm flex light " style="background-color: #eee;align-items: center;" >
				<view style="width: 100%"><u-search placeholder="负责工序/图名/机床" v-model="keyword" bg-color="#fff"
						:show-action="false" :disabled="true" @tap="show=true" searchIconSize="26"
						:inputStyle="inputStyle"></u-search>
				</view>
				<view style="margin-left: 10px; display: flex; flex-direction: column">
					<u-icon @click="reset" name="reload" size="60"></u-icon>
				</view>
			</view>
			<u-tabs style="margin-bottom: 5px;" :list="tabList" :is-scroll="false" :current="current"
				@change="change"></u-tabs>
		</u-sticky>
		<!-- <view class="cu-bar search" style="padding: 10px">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描" :show-action="false"
				@search="confirm"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="show=true" name="list-dot" size="50"></u-icon>
			</view>
		</view> -->
		<u-popup v-model="show" mode="right" length="90%">
			<!-- class="form"  -->
			<u-form class="form" style="padding: 0 10px;" :model="query" ref="uForm" label-position="left">

				<view style="" class="text-border">
					<view class="text text-lg text-green">基本信息</view>
					<!-- <u-form-item label="公司:" prop="companyName" label-width="230">
						<js-select v-model="query.companyCode" :showFilter="false" :items="companySelectList"  placeholder="请选择" :tree="true"
							:label-value="query['company.companyName']" @label-input="query['company.companyName'] = $event"></js-select>
					</u-form-item> -->
					<u-form-item label="机床:" prop="code" label-width="230">
						<u-input placeholder="请输入" v-model="query['code']" type="text"
							maxlength="200"></u-input>
					</u-form-item>

					<u-form-item label="负责人名称" prop="managerNames" label-width="230">
						<u-input placeholder="请输入" v-model="query['managerNames']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item label="负责人工号" prop="managerCodes" label-width="230">
						<u-input placeholder="请输入" v-model="query['managerCods']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item label="图名:" prop="picname" label-width="230">
						<u-input placeholder="请输入" v-model="query['task.orderPic.picname']" type="text"
							maxlength="200"></u-input>
					</u-form-item>
					<u-form-item label="图号:" prop="picno" label-width="230">
						<u-input placeholder="请输入" v-model="query['task.orderPic.picno']" type="text"
							maxlength="200"></u-input>
					</u-form-item>
					<u-form-item label="扫一扫:" prop="picname" label-width="230">
						<u-input placeholder="请输入" v-model="query['picBarCode']" type="text"
							maxlength="200"></u-input>
					</u-form-item>
				</view>
			</u-form>
			<view class="cu-bar"></view>
			<view class=" flex cu-bar tabbar bg-white foot cu-modal-footer">
				<button class="cu-btn  lines-red lg " @click="reset">重置</button>
				<button class="cu-btn  bg-confirm lg margin-left " @click="submit">查询</button>
			</view>
		</u-popup>

		<scroll-view scroll-y="true" @scrolltolower="loadMore" :refresher-enabled="true" :scrolltolower-enabled="true"
			:refresher-triggered="triggered" @refresherrefresh="refresherrefresh" @scrolltoupper="refresherrefresh"
			class="scroll-view-class" :style="{ height: computedScrollViewHeight }" :refresher-threshold="90">
			<view class="scroll-content" ref="scrollContent"
				style="display: flex;flex-direction: column;justify-content: space-between;"
				:style="{ height: computedScrollViewHeight  }">
				<view v-for="(item,index) in list"
					style="position: relative;margin-bottom: 20px;padding: 10px 0 0 0; background: #fff;margin:5px 10px;"
					:key="item.id">
					<view style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
						<view style="font-size: 22px;">
							<u-icon name="grid" size="46" style="margin: 0 5px;"></u-icon>
							{{item.name}}
						</view>
						<view style="font-size: 25px;">
							<dictLabel style="margin-left: 10px;" :value="item.machineStatus"
								dict-type="m8_machine_status">
							</dictLabel>
						</view>
					</view>
					<view v-if="item.task" style="margin-left: 5px;">
						<view v-if="item.task.orderPic">
							<view v-if="item.task.orderPic.picname" class="margin-bottom-sm">
								图名：{{item.task.orderPic.picname || ''}}
							</view>
							<view v-if="item.task.orderPic.picno" class="margin-bottom-sm">
								图号：{{item.task.orderPic.picno || ''}}
							</view>
						</view>
						<view v-if="item.task.oper">
							<view v-if="item.task.oper.operName" class="margin-bottom-sm">
								当前工序：（{{ item.task.sortNum || ''}}){{ item.task.oper.operName || ''}}
							</view>
						</view>
						<view v-if="item.task.oper">
							<view v-if="item.task.oper.operName" class="margin-bottom-sm">
								操作员：{{ item.managerNames || ''}}
							</view>
						</view>
					</view>
					<view style="background-color: #eee;padding: 10px 5px;" class="margin-top-xl">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view class="">
								<u-icon name="clock" size="28"
									style="margin-right: 5px"></u-icon>开始：{{timeFen(item.beginTime)}}
							</view>
							<view style="background: #3c8dbc; color: #fff;padding:0 5px;border-radius: 5px;">
								<u-icon name="clock" size="28"
									style="margin-right: 5px"></u-icon>
								{{getAgoAt(item.beginTime)}}
							</view>
						</view>
						<view style="display: flex;justify-content: space-between;align-items: center;" class="margin-top-xl">
							<view class="">
								<u-icon name="clock" size="28"
									style="margin-right: 5px"></u-icon>结束：{{timeFen(item.endTime)}}
							</view>
							<view style="background: #10c6f3; color: #fff;padding:0 5px;border-radius: 5px;">
								<u-icon name="clock" size="28"
									style="margin-right: 5px"></u-icon>{{getAgoAt(item.endTime)}}
							</view>
						</view>
						<view class="margin-top-xl margin-bottom-sm">
							加工进度：
							<text v-if="item.task">
								{{
							        '   加(' +
							        (item.useJgTime || '无') +
							        ') 完(' +
							        (item.task.sumQty || '无') +
							        ') '
							     }}
								<text v-if="item.task.orderPic">
									{{ '图(' + (item.task.orderPic.iqty || '无') + ')' }}
								</text>
							</text>
						</view>
					</view>
					<view style="width: 100%;padding: 0 5px;" v-if="false">
						<uni-collapse>
							<uni-collapse-item title="负责工序" >
								<view style="padding:5px 10px;" v-for="(item2,index2) in getOperNames(item.operNames)" :key="index2">
									<text>{{item2}}</text>
								</view>
							</uni-collapse-item>
						</uni-collapse>
						
						
					</view>
					
					<u-cell-group :border="false">
						<u-cell-item :border-bottom="false" :title-style="{'font-size': '30rpx'}" :value="timeFen(item,'1')">
							<view slot="title">下次检验时间：
								<!-- <text v-if="item.task">
									{{item.task.nextCheckDate || ''}}
								</text> -->
							</view>
						</u-cell-item>
					</u-cell-group>
					<view class="content-footer">
					  <view class="content-footer-left"></view>
					  <view @click="jcnavigateTo(item)">进入控制台<u-icon name="arrow-right"></u-icon></view>
					</view>

				</view>

				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 80vh;"></u-empty>
			</view>


			<!-- <view v-for="(item,index) in list" class="cu-item shadow "
					style="position: relative;margin-bottom: 10px;" :key="item.id">
					<view class="cu-form-group" style="display: flex;justify-content: space-between;">
						<view
							style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;min-width: 40px;text-align: center;font-style: italic;font-weight: bold">
							{{ index + 1 }}
						</view>
						<view class="">
							<dictLabel style="margin-left: 10px;" :value="item.machineStatus" dict-type="m8_machine_status">
							</dictLabel>
						</view>
					</view>

					<view class="cu-form-group">
						<view class="title">公司：</view>
						<view style="flex: 1;"> {{ item.company?item.company.companyName:""  }}
						</view>
					</view>
					<view class="cu-form-group">
						<view class="title">拣货日期：</view>
						<view style="flex: 1;"> {{ item.date|| ""  }} </view>
					</view>
					<view class="cu-form-group">
						<view class="title">仓库：</view>
						<view style="flex: 1;"> {{ item.basWare && item.basWare.cwhname|| ""  }}
							{{ item.basWare && item.basWare.cwhname ? '('+item.basWare.cwhcode+')' : '' }}</view>
					</view>
					<view class="cu-form-group">
						<view class="">
						</view>
						<view class="">
							<button class="cu-btn lines-green shadow-blur" @click="toForm(item)">
								拣货
							</button>
						</view>
					</view>

				</view>

				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 80vh;"></u-empty>
			</view> -->
		</scroll-view>
		<view style="height: 1px"></view>
		<view style="height: 108rpx"></view>
		<!-- <custom-tab-bar ref="customtab1" :current-index="currentIndex"  @changeTab="handleTabChange" v-if="customTabBar" /> -->
		<view v-if="vuex_config.deviceType == vuex_config.deviceTypeAPP">
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="search" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view>扫一扫</view>
						</view>
					</u-button>

				</movable-view>
			</movable-area>
		</view>
	</view>
</template>
<script>
	import {
		hasPermission
	} from '@/common/fire.js'
	import dictLabel from "@/components/dictLabel.vue";
	import checkVersion from "@/pages/lq-upgrade/checkVersion.js";
	
	import customTabBar from '@/pages/m8/componetns/customTabBar.vue';
	export default {
		components: {
			dictLabel,
			customTabBar
		},
		data() {
			return {
				currentIndex:2,
				 customTabBar:true,
				tabList: [{
						name: '全部'
					},
					{
						name: '忙碌'
					},
					{
						name: '调试'
					},
					{
						name: '空闲'
					},
					{
						name: '我的',
						// count: 5
					},
				],
				current: 0,
				x: 650, //x坐标
				y: 650, //y坐标
				companySelectList: [],
				show: false,
				smshow: false,
				focus: false,
				barCode: "",
				remarks: '',
				czData: {},
				show2: false,
				type: 'text',
				startTime: false, //控制日期显示
				endTime: false, //控制日期显示
				inputStyle: {
					fontSize: '34rpx'
				},
				filterIcon: "/static/image/filter.png",
				keyword: "",
				background: {
					backgroundColor: '#3E97B0',
				},
				list: [],
				itemContent: {},
				query: {
					pageNo: 1,
					pageSize: 5,
					machineStatus: '',
				},
				loadStatus: "loadmore",
				triggered: false,
				flag: false,
				scrollViewHeight: 0,
				headerHeight: 0,
				jhStatusInName: '',
				type: '',
			};
		},
		options:{styleIsolation:'shared'},
		onShow() {
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			// this.query.pageNo = 1;
			// this.loadData();
			
			this.customTabBar = false ;
			setTimeout(()=>{
			    this.customTabBar = true ;
			},100)

		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onLoad(e) {
			this.upgrade();
			this.loadData()
		},
		mounted() {

			this.calculateScrollViewHeight();
		},
		computed: {
			computedScrollViewHeight() {
				return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
			},
		},
		methods: {
			handleTabChange(pagePath) {
			  // 切换页面逻辑，可使用uni.navigateTo等API
			  uni.reLaunch({ url: pagePath });
			},
			//检查版本更新
			upgrade() {
			  // #ifdef APP-PLUS
			  this.$u.api.upgradeCheck().then((res) => {
			    let url = res.data.apkUrl
			      ? res.data.apkUrl
			      : this.vuex_config.xtUrl + res.data.xtUrl;
			    if (res.result == "true") {
			      checkVersion({
			        name: res.data.upTitle, //最新版本名称
			        code: res.data.upVersion, //最新版本号
			        content: `${res.data.upContent}`, //更新内容
			        url, //下载链接
			        // forceUpdate: true, //是否强制升级
			        forceUpdate: res.data.upType == '3'?true:false, //是否强制升级
			      });
			    }
			  });
			  // #endif
			},
			timeFen(date,nextCheckDate){
				if(nextCheckDate == '1'){
					date=date.task?date.task.nextCheckDate:'';
					if(date){
						let str =  date.substring(0, 16);
						return str
					}else{
						return ''
					}
				}else{
					if(date){
						
						let str =  date.substring(0, 16);
						return str
					}else{
						return ''
					}
				}
			},
			getAgoAt(date) {
				if (!date) {
					return '';
				}
				var current_time = new Date().getTime() / 1000;
				var paramDate = Date.parse(date) / 1000;
				var diff = current_time - paramDate;
				var sign = '前';
				if (diff < 0) {
					diff = -1 * diff;
					sign = '后';
				}
				var agoAt = '刚刚';
				var timePoints = [{
						value: 60 * 60 * 24 * 365,
						suffix: '年' + sign,
						max: 2
					},
					{
						value: 60 * 60 * 24 * 30,
						suffix: '月' + sign,
						max: 12
					},
					{
						value: 60 * 60 * 24 * 7,
						suffix: '周' + sign,
						max: 4
					},
					{
						value: 60 * 60 * 24,
						suffix: '天' + sign,
						max: 7
					},
					{
						value: 60 * 60,
						suffix: '小时' + sign,
						max: 23
					},
					{
						value: 60 * 10,
						suffix: '0分钟' + sign,
						max: 5
					},
				];
				for (var i = 0; i < timePoints.length; i++) {
					var point = timePoints[i];
					var mode = Math.floor(diff / point.value);
					if (mode >= 1) {
						agoAt = Math.min(mode, point.max) + point.suffix;
						break;
					}
				}
				return agoAt;
			},
			getOperNames(str){
				let arr =  str.split(",")
				return arr
			},
			change(index) {
				this.query.managerCodes = ''
				this.current = index;
				if (index == 0) {
					this.query.machineStatus = ''
				} else if (index == 1) {
					this.query.machineStatus = 1
				} else if (index == 2) {
					this.query.machineStatus = 3
				} else if (index == 3) {
					this.query.machineStatus = 0
				} else if (index == 4) {
					// this.query.machineStatus = 2 //停机
					this.query.machineStatus = '';
					this.query.managerCodes = this.vuex_user.userCode;
				}
				this.$forceUpdate()
				this.loadData()
			},
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500)
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code

				//判断条形码长度是否大于3
				if (barcode.length > 3) {
					//去除换行符
					let newString = barcode.replace('\n;', '');

					this.barCode = newString;
					this.confirm()
					//将换行符分割成数组
					// const allItems = newString.split('\n');
					// 	//遍历数组，将每一项添加到arr中
					// 	for(let i = 0;i<allItems.length;i++){
					// 		this.arr.push({
					// 			"content":allItems[i],
					// 			"remarks":this.remarks
					// 		})
					// 	}
				}
			},
			confirm() {
				let _this = this;
				if (this.barCode) {
					this.current = 0;
					this.query = {
						pageNo: 1,
						pageSize: 5,
						machineStatus: '',
						picBarCode: this.barCode
					}
					this.loadData()
					// this.current = 0;
					// this.$u.api.m8.machineListData({
					// 	pageNo: 1,
					// 	pageSize: 5,
					// 	machineStatus: '',
					// 	picBarCode: this.barCode
					// }).then((res) => {
					// 	_this.list = res.list
					// });
					setTimeout(() => {
						this.barCode = ''
					}, 500)

				} else {
					_this.sendMp3('sb');
					_this.$refs.jsError.showError("", "条码不能为空", "warn");
				}
			},
			search() {
				let _that = this;
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: function(res) {
						console.log("条码类型：" + res.scanType);
						console.log("条码内容：" + res.result);
						_that.barCode = res.result;
						_that.confirm()
					},
				});
			},


			toForm(item) {
				uni.$off('xwscan', this.BroadcastScanningToObtainData)
				uni.navigateTo({
					url: '/pages/ktnw/jh/list2?djno=' + item.djno,
				})
			},
			reset() {
				this.list = [];
				this.current = 0;
				this.query = {
					pageNo: 1,
					pageSize: 5,
					machineStatus: '',
				};
				this.loadData();
				this.show = false
			},
			submit() {
				this.list = [];
				this.query.pageNo = 1;
				this.query.machineStatus = ''
				this.current = 0;
				
				this.loadData();
				this.show = false
			},
			startConfirm(e) {
				this.query.planArrDate_gte = e.year + '-' + e.month + '-' + e.day;
			},
			endConfirm(e) {
				this.query.planArrDate_lte = e.year + '-' + e.month + '-' + e.day;
			},
			jcnavigateTo(item) {
				// 跳转到工作台页面
				// uni.navigateTo({
				//   url: "/pages/m8/machine/index?item=" + JSON.stringify(item),
				// });
				
				uni.navigateTo({
				  url: "/pages/m8/machine/index?id=" + item.id,
				});
			},
			async calculateScrollViewHeight() {
				try {
					this.headerHeight = 52
					// 计算tabBar高度
					if (this.flag) {
						this.tabBarHeight = 60; // 假设tabbar高度为50px，实际应根据实际情况获取
					} else {
						this.tabBarHeight = 0;
					}
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
				} catch (error) {
					console.error('Error while calculating ScrollView height:', error);
				}
			},

			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.pageNo += 1;
					this.loadData("add");
				}, 100);
			},
			loadData(type) {
				// 循环10次重复赋值  needShListData
				this.$u.api.m8.machineListData(this.query).then((res) => {
					if (res.list.length >= 0) {
						// this.xmList = res.list
						if (res.list.length < 20 || res.list.length == 0) {
							this.loadStatus = "nomore";
						}
						var data = res.list;
						if (type == "add") {
							for (var i = 0; i < data.length; i++) {
								this.list.push(data[i]);
							}
						} else {
							this.list = data;
						}
					}
				});
				
			},
			async refresherrefresh() {
				this.triggered = true;
				this.query.pageNo = 1;
				await this.loadData();
				const scrollTop = 0
				uni.pageScrollTo({
					scrollTop,
					duration: 0,
				});
				setTimeout(() => {
					this.triggered = false;
				}, 500);
			},
		},
		// beforeDestroy() {
		// 	// 清理事件监听器
		// 	try {
		// 		this.$refs.xmInfo.$off('child-mounted-done');
		// 	} catch (e) {
		// 		console.log('Error while unbinding event:', e);
		// 	}
		// }
	};
</script>
<style lang="scss" scoped>
	$all_width: 96rpx;
	$all_height: 96rpx;
	.u-cell{
		padding: 5px 15px 5px 5px !important;
		color: #000 !important;
	}
	/deep/.u-cell__value[data-v-65423b64]{
		font-size: 30rpx !important;
		color: #000 !important;
	}
	 /deep/.uni-collapse-item__title-box[data-v-41027c34]{
		height: 30px !important;
		line-height: 30px !important;
		padding: 0px !important;
		color: #000 !important;
	}

	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透

		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件

			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}

	.text-border {
		border: 2px solid rgb(170, 170, 170);
		border-radius: 5px;
		position: relative;
		padding-top: 20rpx;
		margin-top: 40rpx;
		padding-left: 20rpx;

		.text {
			position: absolute;
			background-color: #fff;
			padding: 10rpx 10rpx;
			top: -25rpx;
			right: 30rpx;
		}
	}
	.content-footer {
	  display: flex;
	  justify-content: space-between;
	  border-top: 2rpx solid #f1f0f0;
	  padding: 36rpx 30rpx;
	  box-sizing: border-box;
	  font-size: 36rpx;
	  color:#3E97B0 ;
	}

	.custom-style {
		// background-color: rgba(25, 190, 107, 0.7);

	}

	.text-xxl {
		font-size: 60rpx;
	}

	.cu-bar {
		min-height: 60px;
	}

	.cu-btn {
		font-size: 16px;
		height: 40px;
	}

	.foot {
		background: #fff;
	}

	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}

	.title {
		width: 260rpx;
	}

	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}

	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}

	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
</style>